package com.njxxted.activiti.common.util;

import com.fasterxml.uuid.EthernetAddress;
import com.fasterxml.uuid.Generators;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.util.UUID;


/**
 * 描述：字符串工具类
 * <p>
 * 作者：HuTongFu
 * 时间：2019/7/12 15:34
 */
public class StringUtils extends org.apache.commons.lang3.StringUtils {

    private static final Logger logger = LoggerFactory.getLogger(StringUtils.class);

    public static String uuidGenerator() {
        UUID uuid = Generators.timeBasedGenerator(EthernetAddress.fromInterface()).generate();
        return String.valueOf(uuid.timestamp());
    }

    /**
     * 将 null 转为 ""
     *
     * @param param 带转换参数
     * @return 转换之后的结果
     */
    public static String convertNull2Str(String param) {
        return org.apache.commons.lang3.StringUtils.isBlank(param) ? "" : param;
    }

    /**
     * 将 null 转为 ""
     *
     * @param param 带转换参数
     * @return 转换之后的结果
     */
    public static String convertNull2Str(Object param) {
        return param == null ? null : param.toString();
    }

    /**
     * 判断字符传表达式是否成立
     *
     * @param condition
     * @return
     */
    public static boolean isTrue(String condition) {
        condition = condition.trim();
        if (StringUtils.isBlank(condition)) {
            return false;
        }
        String substring = condition.substring(condition.length() - 2);
        if ("||".equals(substring) || "&&".equals(substring)) {
            condition = condition.substring(0, condition.length() - 2);
        }
        ScriptEngineManager sem = new ScriptEngineManager();
        ScriptEngine engine = sem.getEngineByName("js");
        try {
            return (boolean) engine.eval(condition.trim());
        } catch (ScriptException e) {
            e.printStackTrace();
            logger.error("判断表达式异常:", e);
            return false;
        }
    }

}
